<template>
  <div class="vehicle-passage-record bg-background text-foreground p-4">
    <h2 class="mb-4 text-2xl font-bold">车辆通行记录</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">

      <QueryForm :model="search" :formItems="formItems" @search="searchVehicles" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
      <button @click="deleteSelected" class="btn btn-destructive">删除</button>
      <button @click="openImportDialog" class="btn btn-secondary">导入</button> -->
      <!-- <button @click="exportData" class="btn btn-secondary">导出</button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">

      <el-table v-loading="loading" :data="displayedVehicleData" style="width: 100%"
        @selection-change="handleSelectionChange" ref="table" align="center" class="data-table"
        :header-cell-style="headerCellStyle">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="EQUIPMENT_CODE" label="设备编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="VEHICLE_TYPE" label="车辆类型" header-align="center" align="center">
          <template #default="scope">
            {{ getVehicleTypeText(scope.row.VEHICLE_TYPE) }}
          </template>
        </el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PASS_TIME" label="通行时间" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.PASS_TIME) }}
          </template>
        </el-table-column>
        <el-table-column prop="PASSAGE_TYPE" label="通行类型" header-align="center" align="center">
          <template #default="scope">
            {{ getPassTypeText(scope.row.PASSAGE_TYPE) }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="通行抓拍" header-align="center" align="center">
          <template #default="scope">

            <span v-if="!scope.row.imgdata">暂无图片</span>
            <el-image v-else style="width: 100px; height: 100px" lazy :src="scope.row.imgdata" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="loadRecordForUpdate(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div class="bg-card text-card-foreground border-border flex items-center justify-between border-t px-4 py-3 sm:px-6">
      <!-- ... pagination content ... -->
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>

    <!-- Add Vehicle Dialog -->
    <el-dialog class="dialog-from" v-model="isEditDialogOpen" title="车辆通行记录编辑" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="updateData" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="80" class="row-item">
              <el-col :span="8">
                <el-form-item label="设备编码：" label-position="top" prop="EQUIPMENT_CODE">
                  <el-input v-model="updateData.EQUIPMENT_CODE" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车辆类型：" label-position="top" prop="VEHICLE_TYPE">
                  <el-select v-model="updateData.VEHICLE_TYPE" placeholder="请选择" clearable>
                    <el-option label="普货车" value="0" />
                    <el-option label="危化品运输车" value="1" />
                    <el-option label="小型车辆" value="2" />
                    <el-option label="应急车辆" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="车牌号码：" label-position="top" prop="LICENSE_PLATE">
                  <el-input v-model="updateData.LICENSE_PLATE" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">

              <el-col :span="8">
                <el-form-item label="通行时间：" label-position="top" prop="PASS_TIME">
                  <input type="datetime-local" id="newPassTime" v-model="updateData.PASS_TIME"
                    class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通行类型：" label-position="top" prop="PASSAGE_TYPE">
                  <el-select v-model="updateData.PASSAGE_TYPE" placeholder="请选择" clearable>
                    <el-option label="进" value="0" />
                    <el-option label="出" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通行抓拍：" label-position="top" prop="PASS_IMG">
                  <div style="display: flex;">
                    <div v-if="updateData.imgdata">
                      <el-image style="width: 100px; height: 100px" lazy :src="updateData.imgdata" fit="cover" />
                    </div>

                    <el-upload :auto-upload="false" class=" upload-demo" action="#" :on-change="handleChange"
                      :show-file-list="false">
                      <div>
                        <span class="attachment-text">附件</span>
                        <el-input v-model="updateData.PASS_IMG" placeholder="点击上传文件" readonly class="input-upload" />
                      </div>
                    </el-upload>


                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="80" class="row-item">

              <el-col :span="8"></el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateRecord">确认</el-button>
          <el-button @click="closeEditDialog">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  -->
    <!-- <Teleport to="body">
      <div v-if="isAddDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">新增车辆通行记录</h3>
            <button @click="closeAddDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <form @submit.prevent="addNewVehicle">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="equipmentCode" class="text-muted-foreground block text-sm font-medium">设备编码：</label>
                <input type="text" id="equipmentCode" v-model="newRecord.EQUIPMENT_CODE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="vehicleType" class="text-muted-foreground block text-sm font-medium">车辆类型：</label>
                <select id="vehicleType" v-model="newRecord.VEHICLE_TYPE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                  <option value="0">普货车</option>
                  <option value="1">危化品运输车</option>
                  <option value="2">小型车辆</option>
                  <option value="3">应急车辆</option>
                </select>
              </div>
              <div>
                <label for="licensePlate" class="text-muted-foreground block text-sm font-medium">车牌号码：</label>
                <input type="text" id="licensePlate" v-model="newRecord.LICENSE_PLATE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="passTime" class="text-muted-foreground block text-sm font-medium">通行时间：</label>
                <input type="datetime-local" id="passTime" v-model="newRecord.PASS_TIME" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="passType" class="text-muted-foreground block text-sm font-medium">通行类型：</label>
                <select id="passType" v-model="newRecord.PASS_TYPE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                  <option value="0">进</option>
                  <option value="1">出</option>
                </select>
              </div>
              <div>
                <label for="passImg" class="text-muted-foreground block text-sm font-medium">通行抓拍：</label>
                <input type="file" id="passImg" @change="handleNewPhotoUpload" accept="image/*"
                  class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mt-1 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
              </div>
              <div>
                <label for="remarks" class="text-muted-foreground block text-sm font-medium">备注：</label>
                <textarea id="remarks" v-model="newRecord.REMARKS"
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1"></textarea>
              </div>
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button type="button" @click="closeAddDialog" class="btn btn-secondary">
                取消
              </button>
              <button type="submit" class="btn btn-primary">确认</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport> -->

    <!-- 修改导入对话框 -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <h3 class="mb-4 text-lg font-bold">导入车辆通行记录</h3>
          <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
            class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
          <div class="flex justify-end space-x-2">
            <button @click="closeImportDialog" class="btn btn-secondary">
              取消
            </button>
            <button @click="importData" class="btn btn-primary">导入</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 查看对话框 -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="车辆通行记录详情" width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="设备编码：">{{ selectedItem.EQUIPMENT_CODE }}</el-descriptions-item>
            <el-descriptions-item label="车辆类型：">{{ getVehicleTypeText(selectedItem.VEHICLE_TYPE)
            }}</el-descriptions-item>
            <el-descriptions-item label="车牌号码：">{{ selectedItem.LICENSE_PLATE }}</el-descriptions-item>
            <el-descriptions-item label="通行时间：">{{ formatDateTime(selectedItem.PASS_TIME) }}</el-descriptions-item>
            <el-descriptions-item label="通行类型：">{{ getPassTypeText(selectedItem.PASSAGE_TYPE) }}</el-descriptions-item>
            <el-descriptions-item label="通行抓拍：">

              <div v-if="selectedItem.PASS_IMG == null">
                {{ selectedItem.PASS_IMG ? selectedItem.PASS_IMG : '无'
                }}
              </div>
              <el-image v-else style="width: 100px; height: 100px" lazy :src="selectedItem.imgdata" :zoom-rate="1.2"
                :max-scale="7" :min-scale="0.2" :initial-index="0" fit="cover" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addExpert">确认</el-button>
          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template> -->
    </el-dialog>

    <!-- 在 template 中添加或修改编辑对话框 -->
    <!-- <Teleport to="body">
      <div v-if="isEditDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">编辑车辆通行记录</h3>
            <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <form @submit.prevent="updateRecord">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label for="editEquipmentCode" class="text-muted-foreground block text-sm font-medium">设备编码：</label>
                <input type="text" id="editEquipmentCode" v-model="updateData.EQUIPMENT_CODE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="editVehicleType" class="text-muted-foreground block text-sm font-medium">车辆类型：</label>
                <select id="editVehicleType" v-model="updateData.VEHICLE_TYPE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                  <option value="0">普货车</option>
                  <option value="1">危化品运输车</option>
                  <option value="2">小型车辆</option>
                  <option value="3">应急车辆</option>
                </select>
              </div>
              <div>
                <label for="editLicensePlate" class="text-muted-foreground block text-sm font-medium">车牌号码：</label>
                <input type="text" id="editLicensePlate" v-model="updateData.LICENSE_PLATE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="editPassTime" class="text-muted-foreground block text-sm font-medium">通行时间：</label>
                <input type="datetime-local" id="editPassTime" v-model="updateData.PASS_TIME" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1" />
              </div>
              <div>
                <label for="editPassType" class="text-muted-foreground block text-sm font-medium">通行类型：</label>
                <select id="editPassType" v-model="updateData.PASS_TYPE" required
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1">
                  <option value="0">进</option>
                  <option value="1">出</option>
                </select>
              </div>
              <div>
                <label for="editPassImg" class="text-muted-foreground block text-sm font-medium">通行抓拍：</label>
                <input type="file" id="editPassImg" @change="handleUpdatePhotoUpload" accept="image/*"
                  class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mt-1 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
              </div>
              <div>
                <label for="editRemarks" class="text-muted-foreground block text-sm font-medium">备注：</label>
                <textarea id="editRemarks" v-model="updateData.REMARKS"
                  class="border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1"></textarea>
              </div>
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button type="button" @click="closeEditDialog" class="btn btn-secondary">
                取消
              </button>
              <button type="submit" class="btn btn-primary">确认</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport> -->

    <!-- Other dialogs... -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/vehicle-pass')

// 搜索相关
const search = ref({
  LICENSE_PLATE: '',
  VEHICLE_TYPE: '',
  PASSAGE_TYPE: '',
})

// 数据相关
const vehicleData = ref([])
const selectAll = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)

// 对话框状态
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isEditDialogOpen = ref(false)

// 导入相关
const importHeaders = ref([])

// 新记录和更新记录
const newRecord = ref({
  VEHICLE_TYPE: '',
  EQUIPMENT_CODE: '',
  LICENSE_PLATE: '',
  PASS_TIME: '',
  PASS_TYPE: '',
  PASS_IMG: null,
  REMARKS: '',
  CREATE_BY: '',
})

const updateData = ref({
  id: '',
  VEHICLE_TYPE: '',
  EQUIPMENT_CODE: '',
  LICENSE_PLATE: '',
  PASS_TIME: '',
  PASS_TYPE: '',
  PASS_IMG: '',
  UPDATE_BY: '',
  files: []
})

const selectedItem = ref(null)
const selectedIds = ref([])

// 计算属性
const totalItems = computed(() => vehicleData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const displayedVehicleData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return vehicleData.value.slice(start, end)
})

// 辅助函数
const getVehicleTypeText = (type) => {
  const types = {
    0: '普货车',
    1: '危化品运输车',
    2: '小型车辆',
    3: '应急车辆',
  }
  return types[type] || ''
}

const getPassTypeText = (type) => {
  return type === '0' ? '进' : type === '1' ? '出' : ''
}

// API 调用函数
const searchVehicles = async () => {
  try {
    loading.value = true
    // const response = await axios.get(`${apiBaseUrl.value}/serach`, {
    //   params: search.value,
    // })
    const response = await axios.get(`${apiBaseUrl.value}/serach`, { params: search.value })
    vehicleData.value = (await Promise.all(response.data.map(async (item) => {
      if (item.PASS_IMG != null && item.PASS_IMG != '') {
        const resimg = await axios.get(`${apiBaseUrl.value}/download/${item.PASS_IMG}`)

        return { ...item, checked: false, imgdata: resimg.data.url }
      } else {
        return { ...item, checked: false, imgdata: item.PASS_IMG }
      }
    })))

    console.log('Received vehicle data:', vehicleData.value)
    // vehicleData.value = response.data
    selectedIds.value = []
    selectAll.value = false
    loading.value = false
    currentPage.value = 1
  } catch (error) {
    console.error('搜索车辆记录失败:', error)
    alert(
      '搜索车辆记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const addNewVehicle = async () => {
  try {
    // 检查必填字段
    if (
      !newRecord.value.VEHICLE_TYPE ||
      !newRecord.value.LICENSE_PLATE ||
      !newRecord.value.PASS_TIME ||
      !newRecord.value.PASS_TYPE
    ) {
      alert('请填写所有必要的字段')
      return
    }

    const formData = new FormData()
    Object.keys(newRecord.value).forEach((key) => {
      if (key === 'PASS_IMG' && newRecord.value[key] instanceof File) {
        formData.append(key, newRecord.value[key])
      } else {
        formData.append(key, newRecord.value[key])
      }
    })

    const response = await axios.post(apiBaseUrl.value, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })

    console.log('Response:', response.data)
    alert(response.data.message || '创建记录成功')
    closeAddDialog()
    await searchVehicles()
  } catch (error) {
    console.error('创建记录失败:', error)
    alert('创建记录失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(
        selectedIds.value.map((ID) =>
          axios.delete(`${apiBaseUrl.value}/${ID}`, {
            data: { UPDATE_BY: 'admin' },
          }),
        ),
      )
      alert('删除成功')
      selectedIds.value = []
      selectAll.value = false
      await searchVehicles()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}

const updateRecord = async () => {
  try {
    // 检查必填字段
    // if (

    //   !updateData.value.LICENSE_PLATE ||
    //   !updateData.value.PASS_TIME ||
    //   !updateData.value.PASS_TYPE
    // ) {
    //   alert('请填写所有必要的字段')
    //   return
    // }

    const formData = new FormData()
    for (const key in updateData.value) {
      if (key !== 'files') {
        formData.append(key, updateData.value[key])
      }
    }
    if (updateData.value?.files) {
      updateData.value.files.forEach((file, index) => {
        formData.append(`files[${index}]`, file)
      })
    }

    const response = await axios.put(
      `${apiBaseUrl.value}/${updateData.value.ID}`,
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
      },
    )

    console.log('Update response:', response.data)
    alert(response.data.message || '更新记录成功')
    closeEditDialog()
    await searchVehicles()
  } catch (error) {
    console.error('更新记录失败:', error)
    alert('更新记录失败: ' + (error.response?.data?.message || error.message))
  }
}
const handleChange = (file, fileList) => {
  // 处理文件上传后的逻辑
  updateData.value.files = [file.raw]
  updateData.value.PASS_IMG = file.name // 这里可以根据需要调整

}
// 事件处理函数
const resetSearch = () => {
  search.value = {
    LICENSE_PLATE: '',
    VEHICLE_TYPE: '',
    PASSAGE_TYPE: '',
  }
  searchVehicles()
}

const openAddDialog = () => {
  resetNewRecord() // 重置 newRecord
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  resetNewRecord()
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importHeaders.value = []
}

const importFile = ref(null)

const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet)

    try {
      console.log('导入数据 - 发送数据:', jsonData)
      const response = await axios.post(`${apiBaseUrl.value}/import`, jsonData)
      console.log('导入数据 - 接收到的响应:', response.data)
      alert('数据导入成功')
      closeImportDialog()
      await searchVehicles()
    } catch (error) {
      console.error('Error importing data:', error)
      alert('导入数据失败：' + error.message)
    }
  }
  reader.readAsArrayBuffer(importFile.value)
}

// 修改 exportData 函数
const exportData = () => {
  const dataToExport = vehicleData.value.map((item) => ({
    设备编码: item.EQUIPMENT_CODE,
    车辆类型: getVehicleTypeText(item.VEHICLE_TYPE),
    车牌号码: item.LICENSE_PLATE,
    通行时间: formatDateTime(item.PASS_TIME),
    通行类型: getPassTypeText(item.PASSAGE_TYPE),
    备注: item.REMARKS,
  }))

  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '车辆通行记录')

  // 生成二进制字符串作为文件内容
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为Blob对象
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '车辆通行记录.xlsx'
  link.click()
}

// 辅助函数：将字符串转换为ArrayBuffer
function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}

const viewDetails = (item) => {
  selectedItem.value = { ...item }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = null
}

const loadRecordForUpdate = (item) => {
  console.log(item)
  updateData.value = {
    ...item,
    PASS_TIME: formatDateTimeForInput(item.PASS_TIME),
  }
  isEditDialogOpen.value = true
}

const resetUpdateData = () => {
  updateData.value = {
    ID: '',
    VEHICLE_TYPE: '',
    EQUIPMENT_CODE: '',
    LICENSE_PLATE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: '',
    UPDATE_BY: '',
  }
}

const handleUpdatePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    updateData.value.PASS_IMG = file
  }
}

const changePageSize = () => {
  currentPage.value = 1
  searchVehicles()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // searchVehicles()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // searchVehicles()
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    searchVehicles()
  }
}

const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = vehicleData.value.map((item) => item.ID)
  }
  selectAll.value = !selectAll.value
}

const toggleItemSelection = (item) => {
  const index = selectedIds.value.indexOf(item.ID)
  if (index === -1) {
    selectedIds.value.push(item.ID)
  } else {
    selectedIds.value.splice(index, 1)
  }
  selectAll.value = selectedIds.value.length === vehicleData.value.length
}

// 添加处理新照片上传的函数
const handleNewPhotoUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    newRecord.value.PASS_IMG = file
  }
}

// 修改 resetNewRecord 函数
const resetNewRecord = () => {
  newRecord.value = {
    VEHICLE_TYPE: '',
    EQUIPMENT_CODE: '',
    LICENSE_PLATE: '',
    PASS_TIME: '',
    PASS_TYPE: '',
    PASS_IMG: null,
    REMARKS: '',
    CREATE_BY: '',
  }
}

// 添加这个函数
const closeEditDialog = () => {
  isEditDialogOpen.value = false
  resetUpdateData()
}

// 添加这个函数
const confirmDelete = async (ID) => {
  if (confirm('确定要删除这条记录吗？')) {
    try {
      await axios.delete(`${apiBaseUrl.value}/${ID}`, {
        data: { UPDATE_BY: 'admin' }, // 假设我们需要传递更新人信息
      })
      alert('删除成功')
      await searchVehicles()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}

// 添加格式化日期时间的辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '车辆类型：',
    model: 'VEHICLE_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '请选择', value: '' },
      { label: '普货车', value: '0' },
      { label: '危化品运输车', value: '1' },
      { label: '小型车辆', value: '2' },
      { label: '应急车辆', value: '3' },
    ],
  },
  {
    label: '通行类型：',
    model: 'PASSAGE_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: '进', value: '0' },
      { label: '出', value: '1' },
    ],
  },
])
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rules = {
  EQUIPMENT_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  STAFF_CODE: [
    { required: true, message: '请输入人员编码', trigger: 'blur' },
  ],
  STAFF_NAME: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' },
  ],
  STAFF_TYPE: [
    { required: true, message: '请输入人员类型', trigger: 'change' },
  ],
  PASS_TIME: [
    { required: true, message: '请输入通行时间', trigger: 'change' },
  ],
  PASS_TYPE: [
    { required: true, message: '请输入通行类型', trigger: 'change' },
  ],
}
const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// 生命周期钩子
onMounted(() => {
  searchVehicles()
})

// 修改按钮样式的计算属性
const btnClasses = computed(() => {
  return 'px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out'
})

const btnPrimaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-primary text-primary-foreground hover:bg-primary/90',
  ]
})

const btnSecondaryClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-secondary text-secondary-foreground hover:bg-secondary/80',
  ]
})

const btnDestructiveClasses = computed(() => {
  return [
    btnClasses.value,
    'bg-destructive text-destructive-foreground hover:bg-destructive/90',
  ]
})

// Update your template to use these computed properties for button classes
</script>

<style scoped>
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>
